<?php
class cartoon_util_upload  {
	
	public static $SIZES = array(
					'big'=>array('width'=>200,'heigth'=>200),
					'mid'=>array('width'=>131,'heigth'=>178),
					'small'=>array('width'=>60,'heigth'=>60)
	);
	
	public static $cute = true;
	
	/**
	 * ERROR code
	 *
	 */
	const ERROR_UPLOAD 						= 1000;
	const ERROR_IMGSIZE 					= 1001;
	const ERROR_FILETYPE 					= 1002;
	const ERROR_REMOTE_TIMESTAMP_EXPIRES 	= 1003;
	const ERROR_REMOTE_CHECKSUM 			= 1004;
	const ERROR_ILLEGAL						= 1005;
		
	public static function get_filename($id,$ext = NULL){
		return "cartoon_cover_".$id.($ext?'.'.$ext:'');
	}
	
	/**
	 * 设置图片裁剪的尺寸
	 *
	 * @param unknown_type $mid
	 * @param unknown_type $small
	 * @param unknown_type $big
	 */
	public static function setCuteConf($size = array('big'=>array('width'=>0,'heigth'=>0),'mid'=>array('width'=>0,'heigth'=>0),'small'=>array('width'=>0,'heigth'=>0))){
		if(intval($size['big']['width'])>0){
			self::$SIZES['big'] = $size['big'];
			self::$cute = true;
		}
		if(intval($size['mid']['width'])>0){
			self::$SIZES['mid'] = $size['mid'];
			self::$cute = true;
		}
		if(intval($size['small']['width'])>0){
			self::$SIZES['small'] = $size['small'];
			self::$cute = true;
		}
	}
	
	/**
	 * 获得图片磁盘目录路径
	 *
	 * @param int $uid
	 * @param string $root_path
	 * @return string
	 */
	public static function get_real_path($id){
		return self::get_directory($id)."/";
	}
	
	
	public static function check_file_content($file){
		$type = exif_imagetype($file);
		return ($type == IMAGETYPE_JPEG or 
		   $type == IMAGETYPE_GIF or 
		   $type == IMAGETYPE_BMP or 
		   $type == IMAGETYPE_JPEG2000 or 
		   $type == IMAGETYPE_PNG);
	}
	
	public static function check_file_extensions($ext){
		$extensions = array('.jpg', '.bmp', '.gif', '.png', '.jpeg');
		$ext = strtolower($ext);
		return (in_array($ext, $extensions));
	}
	
	public static function get_directory($id){
		$hex = dechex($id);
		$hex = str_repeat('0', 8-strlen($hex)).$hex;
		$regex = '`([\da-z]{2})([\da-z]{2})([\da-z]{2})([\da-z]{2})`';
		preg_match($regex, $hex, $match);
		array_pop($match);
		array_shift($match);
		return implode($match, '/');
	}
	
	/**
 * 获得文件路径信息
 *
 * @param string $path
 * @return string[] [0]路径目录 [1]主文件名 [2]扩展名
 */
	function getFilePathInfo($path){
		$ret = array();
		$seperator = '/';
		$dot = '.';
		$pos1 = strrpos($path, $seperator);
		$pos2 = strrpos($path, $dot);

		if($pos1 !== false){
			$ret['path'] = substr($path, 0, $pos1+1);
			if($pos2 !== false && $pos2 > $pos1){
				$ret['name'] = substr($path, $pos1 +1, $pos2-$pos1-1);
				$ret['extension'] = substr($path, $pos2);
			}else{
				$ret['name'] = substr($path, $pos1 +1);
			}
		}else{
			if($pos2 !== false){
				$ret['name'] = substr($path, 0, $pos2);
				$ret['extension'] = substr($path, $pos2);
			}else{
				$ret['name'] = $path;
			}
		}
		return $ret;
	}

	/**
	 * 上传漫画封面
	 * @param string $file
	 * @param int $id
	 */
	public static function upload_cover($file,$id){		
		//上传目录
		$path = self::get_real_path($id);
		$path	=	'cartoon_cover/'.$id.'/';
		self::$SIZES['big'] = array('width'=>215,'heigth'=>280);
		self::$SIZES['mid'] = array('width'=>131,'heigth'=>178);
		if(!is_dir($path)){
			$path = cartoon_util_cache::mkdirs($path);
		}
		
		return self::upload_file($file,$path,self::get_filename($id),true);
		
	}
	
	/**
	 * 上传漫画图片
	 * @param string $file
	 * @param int $id
	 */
	
	public static function upload_photo($file,$chapter_id){		
		//上传目录
		$path = 'm_'.date('m',CURRENT_TIME).'/'.$chapter_id.'/';//self::get_real_path($chapter_id);
//		echo $path;
		if(!is_dir(CT_UPLOAD_PATH.$path)){
			cartoon_util_cache::mkdirs(CT_UPLOAD_PATH.$path);
		}
//		echo $path;
		$_s = md5($path.$chapter_id.rand(1,10000));
		return self::upload_file($file,$path,substr($_s,0,rand(10,strlen($_s)-10)),self::$cute,CT_UPLOAD_PATH);
		
	}
	/**
	 * 上传文件
	 *
	 * @param unknown_type $file
	 * @param unknown_type $uid
	 * @param unknown_type $cute
	 * @param unknown_type $mid
	 * @param unknown_type $small
	 * @return unknown
	 */
	
	public static  function upload_file($file,$destPath,$destFilename,$cute = false,$pre_path = CT_UPLOAD_PATH){
        $file = $_FILES[$file];
        !$pre_path && $pre_path = CT_UPLOAD_PATH;
		if(is_file($file['tmp_name']) && is_uploaded_file($file['tmp_name'])){
			$info = self::getFilePathInfo($file['name']);
			if(self::check_file_extensions($info['extension'])){
				if(self::check_file_content($file['tmp_name'])){
					$destfile = $pre_path.$destPath.$destFilename.$info['extension'];
					if(move_uploaded_file($file['tmp_name'],$destfile)){
						if($cute && self::$cute){
							self::cutImage($destfile,$destfile);//裁图
						}
						return array('result'=>true,'url'=>$destPath.$destFilename.$info['extension'],'message'=>'');
					}else{
						return array('result'=>false,'message'=>self::ERROR_UPLOAD);
						unlink($file['tmp_name']);
					}
				}
				else{
					return array('result'=>false,'message'=>self::ERROR_FILETYPE);
					unlink($file['tmp_name']);
				}
			}else{
				return array('result'=>false,'message'=>self::ERROR_FILETYPE);
				unlink($file['tmp_name']);
			}
		}else{
			return array('result'=>false,'message'=>self::ERROR_UPLOAD);
			unlink($file['tmp_name']);
		}
	}

    
	/**
	 * 裁剪图片
	 *
	 * @param unknown_type $source		原始图
	 * @param unknown_type $dest		存放的目标图片
	 */
	public function cutImage($source,$dest=NULL){
		try{
			$dest = $dest?$dest:$source;
			$cute = new cartoon_util_resize($source);
			$ext = pathinfo($dest, PATHINFO_EXTENSION);
			$file_path = substr($dest,0,strpos($dest,$ext)-1);
			//大图
			if(self::$SIZES['big']['width']>0){
				$file_name = $file_path."_big.".$ext;
				$cute->setNewImage($file_name);
				$cute->setNewSize(self::$SIZES['big']['heigth'],self::$SIZES['big']['width']);
				$cute->make();
			}
			
			/**
			 * 中图
			 */
			
			if(self::$SIZES['mid']['width']>0){
				$file_name = $file_path."_mid.".$ext;
				$cute->setNewImage($file_name);
				$cute->setNewSize(self::$SIZES['mid']['heigth'],self::$SIZES['mid']['width']);
				$cute->make();
			}
			
			/**
			 * 小图
			 */
			
			if(self::$SIZES['small']['width']>0){
				$file_name = $file_path."_small.".$ext;
				$cute->setNewImage($file_name);
				$cute->setNewSize(self::$SIZES['small']['heigth'],self::$SIZES['small']['width']);
				$cute->make();
			}
		}
		catch (Exception $e){
			echo $e;
		}
	}
	
	
	/**
	 * 获取图片地址
	 *
	 * @param unknown_type $file
	 * @param unknown_type $type
	 * @return unknown
	 */
	public static function getImageUrl($file,$type = 'mid'){
		$fileinfo = pathinfo($file);
		return $fileinfo['dirname'].'/'.$fileinfo['filename'].'_'.$type.'.'.$fileinfo['extension'];
	} 	
	/**
	 * 获取图片的缩略图列表
	 *
	 * @param unknown_type $file
	 * @param unknown_type $type 	
	 */
	public static function getUrl($file,$type = 'mid',$thumeb = true){
		if(false === strpos($file,'http')){
			$file = UPLOAD_DOMAIN.'/'.$file;
		}
		if($thumeb===false) return $file;
		$pattern =	'/([^http(s)?\/\/].*)(\.[a-zA-Z]{2,4})/';
		return  preg_replace($pattern,"\\1_".$type."\\2",$file);
	}
}
?>